package com.kinptm.masterclock.ui;

import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.doomonafireball.betterpickers.radialtimepicker.RadialPickerLayout;
import com.doomonafireball.betterpickers.radialtimepicker.RadialTimePickerDialog;
import com.kinptm.masterclock.Intents;
import com.kinptm.masterclock.R;
import com.kinptm.masterclock.bean.AlarmClock;
import com.kinptm.masterclock.bean.AlarmNotice;
import com.kinptm.masterclock.db.DbHelper;
import com.kinptm.masterclock.ui.fragment.SelectAlarmNoticeFragment;
import com.kinptm.masterclock.utils.AlarmUtil;
import com.kinptm.masterclock.utils.Ln;
import com.kinptm.masterclock.utils.ViewUtil;

import org.joda.time.DateTime;

import java.io.IOException;
import java.util.TreeSet;

@SuppressWarnings("deprecation")
public class AlarmClockDetailsActivity extends SherlockFragmentActivity implements View.OnClickListener,
        CompoundButton.OnCheckedChangeListener, SelectAlarmNoticeFragment.OnSelectAlarmNoticeListener, SeekBar.OnSeekBarChangeListener {

    private EditText mTitleEditText;
    private TextView mTimeTextView;
    private SeekBar mVolumeSeekBar;
    private EditText mRemarkEditText;
    private TextView mSoundTextView;
    private CheckBox isSoundCheckBox;
    private CheckBox isVibrateCheckBox;

    private AlarmClock mAlarmClock;
    private DbHelper mDbHelper;
    private DateTime mAlarmDateTime;
    private MediaPlayer mMediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_clock_details);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        mDbHelper = DbHelper.getInstance();

        mTitleEditText = ViewUtil.findView(this, R.id.alarm_clock_details_title_et);
        mTimeTextView = ViewUtil.findView(this, R.id.alarm_clock_details_time_tv);
        mSoundTextView = ViewUtil.findView(this, R.id.alarm_clock_details_sound_tv);
        mVolumeSeekBar = ViewUtil.findView(this, R.id.alarm_clock_details_volume_sb);
        mRemarkEditText = ViewUtil.findView(this, R.id.alarm_clock_details_remark_et);
        isSoundCheckBox = ViewUtil.findView(this, R.id.alarm_clock_details_sound_enable_cb);
        isVibrateCheckBox = ViewUtil.findView(this, R.id.alarm_clock_details_vibrate_enable_cb);

        ViewUtil.findViewAndClick(this, R.id.alarm_clock_details_repeat_day1_ctv, this);
        ViewUtil.findViewAndClick(this, R.id.alarm_clock_details_repeat_day2_ctv, this);
        ViewUtil.findViewAndClick(this, R.id.alarm_clock_details_repeat_day3_ctv, this);
        ViewUtil.findViewAndClick(this, R.id.alarm_clock_details_repeat_day4_ctv, this);
        ViewUtil.findViewAndClick(this, R.id.alarm_clock_details_repeat_day5_ctv, this);
        ViewUtil.findViewAndClick(this, R.id.alarm_clock_details_repeat_day6_ctv, this);
        ViewUtil.findViewAndClick(this, R.id.alarm_clock_details_repeat_day7_ctv, this);

        mTimeTextView.setOnClickListener(this);
        mSoundTextView.setOnClickListener(this);
        isSoundCheckBox.setOnCheckedChangeListener(this);
        isVibrateCheckBox.setOnCheckedChangeListener(this);

        mAlarmClock = (AlarmClock) getIntent().getSerializableExtra(Intents.ALARM.EXTRA_ALARM_CLOCK);
        if (mAlarmClock == null) {
            mAlarmClock = new AlarmClock(this);
            mAlarmClock.setTitle("闹钟" + (mDbHelper.getAlarmClockDao().countOf() + 1));
            mAlarmDateTime = DateTime.now();
        } else {
            mAlarmDateTime = new DateTime(mAlarmClock.getAlarmMillis());
        }

        ViewUtil.setText(mTitleEditText, mAlarmClock.getTitle());
        ViewUtil.setText(mTimeTextView, mAlarmDateTime.toString("HH:mm"));
        ViewUtil.setText(mSoundTextView, mAlarmClock.getSoundTitle());

        mVolumeSeekBar.setProgress(mAlarmClock.getVolume());
        mVolumeSeekBar.setOnSeekBarChangeListener(this);
        ViewUtil.setText(mRemarkEditText, mAlarmClock.getRemark());
        isSoundCheckBox.setChecked(mAlarmClock.isSound());
        isVibrateCheckBox.setChecked(mAlarmClock.isVibrate());
        setRepeatDaysView(mAlarmClock.getRepeat());

        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setLooping(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.alarm_clock_details, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.action_alarm_clock_details_ok:
                mAlarmClock.setTitle(mTitleEditText.getText().toString());
                mAlarmClock.setRepeat(getRepeatDays());
                mAlarmClock.setVolume(mVolumeSeekBar.getProgress());
                mAlarmClock.setRemark(mRemarkEditText.getText().toString());

                //防止因停留时间过长而导致时间误差
                DateTime dateTime = DateTime.now().withTime(mAlarmDateTime.getHourOfDay(), mAlarmDateTime.getMinuteOfHour(), 0, 0);
                mAlarmClock.setAlarmMillis(dateTime.getMillis());

                AlarmUtil.nextAlarmClock(mAlarmClock);

                mDbHelper.getAlarmClockDao().createOrUpdate(mAlarmClock);

                if (mAlarmClock.isEnable()) {
                    AlarmUtil.showIntervalTime(mAlarmClock);
                    AlarmUtil.cancel2AlarmClock(mAlarmClock);
                    AlarmUtil.plan2AlarmClock(mAlarmClock);
                } else {
                    AlarmUtil.cancel2AlarmClock(mAlarmClock);
                }
                Ln.d("新增的闹钟时间 -> %s , 重复周期 -> %s", new DateTime(mAlarmClock.getAlarmMillis()).toString("yyyy-MM-dd HH:mm:ss"), mAlarmClock.getRepeat());

                Intent data = new Intent();
                data.putExtra(Intents.ALARM.EXTRA_ADD_ALARM_CLOCK, mAlarmClock);
                setResult(Activity.RESULT_OK, data);
                finish();
                break;
            case R.id.action_alarm_clock_details_cancel:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private TreeSet<Integer> getRepeatDays() {
        TreeSet<Integer> repeat = new TreeSet<Integer>();
        int[] ids = new int[]{R.id.alarm_clock_details_repeat_day1_ctv,
                R.id.alarm_clock_details_repeat_day2_ctv,
                R.id.alarm_clock_details_repeat_day3_ctv,
                R.id.alarm_clock_details_repeat_day4_ctv,
                R.id.alarm_clock_details_repeat_day5_ctv,
                R.id.alarm_clock_details_repeat_day6_ctv,
                R.id.alarm_clock_details_repeat_day7_ctv};
        for (int i = 0; i < ids.length; i++) {
            CheckedTextView check = ViewUtil.findView(this, ids[i]);
            if (check.isChecked()) {
                repeat.add(i + 1);
            }
        }
        return repeat;
    }

    private void setRepeatDaysView(TreeSet<Integer> days) {
        TreeSet<Integer> repeat = new TreeSet<Integer>();
        int[] ids = new int[]{R.id.alarm_clock_details_repeat_day1_ctv,
                R.id.alarm_clock_details_repeat_day2_ctv,
                R.id.alarm_clock_details_repeat_day3_ctv,
                R.id.alarm_clock_details_repeat_day4_ctv,
                R.id.alarm_clock_details_repeat_day5_ctv,
                R.id.alarm_clock_details_repeat_day6_ctv,
                R.id.alarm_clock_details_repeat_day7_ctv};
        for (int day : days) {
            CheckedTextView check = ViewUtil.findView(this, ids[day - 1]);
            check.setChecked(true);
            setRepeatDayBg(check);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.alarm_clock_details_sound_enable_cb:
                mAlarmClock.setSound(isChecked);
                break;
            case R.id.alarm_clock_details_vibrate_enable_cb:
                mAlarmClock.setVibrate(isChecked);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.alarm_clock_details_time_tv:
                RadialTimePickerDialog radialTimePickerDialog = RadialTimePickerDialog.newInstance(new RadialTimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
                        DateTime dateTime = mAlarmDateTime = DateTime.now().withTime(hourOfDay, minute, 0, 0);
                        ViewUtil.setText(mTimeTextView, dateTime.toString("HH:mm"));
                    }
                }, mAlarmDateTime.getHourOfDay(), mAlarmDateTime.getMinuteOfHour(), true);
                radialTimePickerDialog.show(getSupportFragmentManager(), "time");
                break;

            case R.id.alarm_clock_details_repeat_day1_ctv:
            case R.id.alarm_clock_details_repeat_day2_ctv:
            case R.id.alarm_clock_details_repeat_day3_ctv:
            case R.id.alarm_clock_details_repeat_day4_ctv:
            case R.id.alarm_clock_details_repeat_day5_ctv:
            case R.id.alarm_clock_details_repeat_day6_ctv:
            case R.id.alarm_clock_details_repeat_day7_ctv:
                CheckedTextView check = (CheckedTextView) v;
                check.setChecked(!check.isChecked());
                setRepeatDayBg(check);
                break;
            case R.id.alarm_clock_details_sound_tv:
                SelectAlarmNoticeFragment fragment = SelectAlarmNoticeFragment.newInstance();
                fragment.setOnSelectAlarmNoticeListener(this);
                getSupportFragmentManager().beginTransaction().add(fragment, "alarm_notice").commit();
                break;
        }
    }

    private void setRepeatDayBg(CheckedTextView check) {
        check.setBackgroundColor(check.isChecked() ?
                getResources().getColor(R.color.repeat_day_checked) :
                getResources().getColor(android.R.color.transparent));
    }

    @Override
    public void onSelected(AlarmNotice notice) {
        setSound(notice.getUri(), notice.getTitle());
    }

    private void setSound(Uri uri, String title) {
        mAlarmClock.setSoundUri(uri == null ? "" : uri.toString());
        mAlarmClock.setSoundTitle(title);
        mSoundTextView.setText(title);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        mMediaPlayer.setVolume(progress / 100f, progress / 100f);
        Ln.e("onProgressChanged");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        Ln.e("onStartTrackingTouch -> "+mAlarmClock.getSoundUri());
        if (TextUtils.isEmpty(mAlarmClock.getSoundUri()))
            return;
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(this, Uri.parse(mAlarmClock.getSoundUri()));
            mMediaPlayer.setVolume(seekBar.getProgress() / 100f, seekBar.getProgress() / 100f);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Ln.e("onStopTrackingTouch");
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
        }
    }
}
